package com.laicunba.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.laicunba.pojo.TaskDO;
import com.laicunba.service.TaskService;
import com.laicunba.service.task.TaskExecutor;

@Component
public class TaskServiceImpl extends BaseServiceImpl implements TaskService {

	private Map<String, TaskExecutor> taskExecutors;
	private TaskExecutor defaultExecutor;

	@Autowired
	public void setTaskExecutor(TaskExecutor[] taskExecutorList) {
		taskExecutors = new HashMap();
		for (TaskExecutor taskExecutor : taskExecutorList) {
			taskExecutors.put(taskExecutor.getType(), taskExecutor);
		}
		defaultExecutor = taskExecutors.get("DEFAULT");
	}

	@Override
	public boolean execute(TaskDO task, Object context) {
		try {
			TaskExecutor taskExecutor = taskExecutors.get(task.getType());
			if (taskExecutor == null) {
				taskExecutor = defaultExecutor;
			}
			return taskExecutor.execute(task, context);

		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public List<TaskDO> findRunAble(String type, int limit) {
		Map map = new HashMap();
		map.put("type", type);
		map.put("limit", limit);
		return queryDao.selectList("TASK.findRunAble", map);
	}

	@Override
	public List<TaskDO> findRunAble(String uid, String type, int limit) {
		Map map = new HashMap();
		map.put("type", type);
		map.put("limit", limit);
		map.put("uid", uid);
		return queryDao.selectList("TASK.findRunAbleByUid", map);
	}
}
